package com.pth.dao.impl;

import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.pth.dao.KnowledgeDAO;
import com.pth.model.Knowledge;

public class KnowledgeDAOImpl implements KnowledgeDAO {

	private HibernateTemplate hibernateTemplate;
	
	public void delete(Knowledge knowledge) {

		hibernateTemplate.delete(knowledge);
		
		
	}

	@SuppressWarnings("unchecked")
	public List<Knowledge> getAllKnowledges(final int pagesize,final int offset) {

		final String hqlString="from Knowledge k order by k.publishtime desc";
		
		List<Knowledge> list=hibernateTemplate.executeFind(new HibernateCallback() {

			public Object doInHibernate(Session arg0) throws HibernateException,
					SQLException {

				return arg0.createQuery(hqlString).setFirstResult(offset).setMaxResults(pagesize).list();
				
			}
		});
		
		return list;
		
	}

	
	public int getAllNum() {

		return hibernateTemplate.find("from Knowledge").size();
		
	}

	public Knowledge getKnowledgeByid(int id) {

		return hibernateTemplate.get(Knowledge.class, id);
		
	}

	public void save(Knowledge knowledge) {


		hibernateTemplate.save(knowledge);
		
	}

	public void update(Knowledge knowledge) {

		hibernateTemplate.update(knowledge);
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	@SuppressWarnings("unchecked")
	public List<Knowledge> getKnowledgesByScanNum(final int pagesize,final int offset) {


		final String hqlString="from Knowledge k order by k.scannum desc";
		
		List<Knowledge> list=hibernateTemplate.executeFind(new HibernateCallback() {

			public Object doInHibernate(Session arg0) throws HibernateException,
					SQLException {

				return arg0.createQuery(hqlString).setFirstResult(offset).setMaxResults(pagesize).list();
				
			}
		});
		
		return list;
		
		
	}

	@SuppressWarnings("unchecked")
	public List<Knowledge> getAllKnowledges() {

		return hibernateTemplate.find("from Knowledge");
		
	}

}
